package com.game;

import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.swing.ImageIcon;
import javax.swing.JPanel;

//拼图板
public class GamePanel extends JPanel {

	private static GamePanel panel;
	private static List<GameButton> btnList;
	private GamePanel(){}
	
	//初始化 拼图板
	public static GamePanel init()throws Exception{
		panel=new GamePanel();
		//设置panel布局管理
		GridLayout grid=new GridLayout(GameConstant.ROW_NUM, GameConstant.COL_NUM);
		grid.setHgap(0);
		grid.setVgap(0);
		panel.setLayout(grid);
		//加载图片
		InputStream is=GamePanel.class.getResourceAsStream(GameConstant.IMG_PATH);
		SplitImage.loadImage(is);
		//分割图片
		List<Map<String,Object>> imageList=SplitImage.splitImage(
									GameConstant.ROW_NUM, GameConstant.COL_NUM, 
									GameConstant.IMG_WIDTH, GameConstant.IMG_HEIGHT);
		
		//随机打乱顺序
		SplitImage.randomImageList();
		
		//生成按钮
		genButton(imageList);
		return panel;
	}
	
	// 重载初始化方法
	public static GamePanel init(String path)throws Exception{
		panel=new GamePanel();
		
		//设置panel布局管理
		GridLayout grid=new GridLayout(GameConstant.ROW_NUM, GameConstant.COL_NUM);
		grid.setHgap(0);
		grid.setVgap(0);
		panel.setLayout(grid);
		//加载图片
		InputStream is= new FileInputStream(new File(path));
		SplitImage.loadImage(is);
		//分割图片
		List<Map<String,Object>> imageList=SplitImage.splitImage(GameConstant.ROW_NUM, GameConstant.COL_NUM,	GameConstant.IMG_WIDTH, GameConstant.IMG_HEIGHT);
		//随机打乱顺序
		SplitImage.randomImageList();
		//生成按钮
		genButton(imageList);
		return panel;
	}
	
	//生成按钮
	public static void genButton(List<Map<String,Object>> imageList){
		//按钮集合
		btnList=new ArrayList<GameButton>();
		
		for(int i=0;i<imageList.size();i++){
			Map<String,Object> map=imageList.get(i);
			BufferedImage img=(BufferedImage) map.get("image");
			ImageIcon icon=new  ImageIcon(img);
			if(i==11){//设计最后一个按钮为 无图片
				icon=null;
			}
			GameButton btn=new GameButton(icon);
			//设置按钮大小和图片相同 （要点）
			btn.setPreferredSize(new Dimension(img.getWidth(),img.getHeight()));
			btn.setBtnIndex(i);		//保存按钮固定索引
			if(icon==null){
				btn.setHasIcon(false);//标示按钮无图片
			}else{
				btn.setHasIcon(true);
			}
			btn.addActionListener(new BtnListener());//按钮事件监听
			panel.add(btn);//加入panel
			btnList.add(btn);//加入按钮集合
		}
	}

	//获取 按钮list
	public static List<GameButton> getBtnList() {
		return btnList;
	}
	
}
